<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><span style="color: #1f120b">人员管理</span></el-breadcrumb-item>
        </el-breadcrumb>
        <el-card style="margin-top: 4vh">
            <!--            功能栏-->
            <el-row type="flex" align="middle">
                <el-col :span="6">
                    <span style="font-size: 14px;color:#280404">选择身份：</span>
                    <el-dropdown placement="bottom" @command="selectRole">
                        <el-button split-button class="sel_btn">
                            {{this.ByRoleName}}<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu class="list" slot="dropdown">
                            <el-dropdown-item v-for="(item,index) in RoleList"
                                              v-text="item.name"
                                              :command="item"
                                              :key="index"></el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>
                <el-col :span="6" :offset="2">
                    <el-input placeholder="请输入搜索内容" v-model="queryInfo.searchInfo" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <el-col :offset="1" :span="3">
                    <el-button class="addcount" @click="handleExport">
                        <svg class="icon_add" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                            <path d="M10.0088731,5.83850932 L18.2608696,14.1259982 L14.72937,14.1259982 L14.72937,20 L5.27062998,20 L5.25288375,14.1259982 L1.77462287,14.1259982 L10.0088731,5.83850932 Z M19.4321207,0 L19.4321207,2.36024844 L0.567879336,2.36024844 L0.567879336,0 L19.4321207,0 Z" id="形状" fill="#FFFFFF"></path>
                        </svg>
                        导出人员列表
                    </el-button>
                </el-col>
                <el-col :span="4" :offset="1">
                    <el-button @click="toAdd = true" plain>
                        <i class="el-icon-plus"></i>
                        新增用户
                    </el-button>
                </el-col>
            </el-row>
            <el-scrollbar :native="false">
                <!--           展示所有隐患-->
                <el-table
                        v-loading="loading"
                        element-loading-text="拼命加载中"
                        element-loading-spinner="el-icon-loading"
                        id="exportExcel"
                        ref="multipleTable"
                        :data="pagetestlist"
                        tooltip-effect="dark"
                        stripe
                        style="width: 100%;margin-top: 4vh"
                        :header-cell-style="{color: '#000000E6'}"
                        @selection-change="handleSelectionChange"
                        :row-key="getRowKeys"
                        :expand-row-keys="expands"
                        @expand-change="expandChange">
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-form  v-loading=""
                                      element-loading-text="拼命加载中"
                                      element-loading-spinner="el-icon-loading"
                                      label-position="left"  style="margin-left: 40px">
                                <el-form-item >
                                     <span slot="label">
                                         <i class="el-icon-bank-card"></i>
                                         用户名
                                    </span>
                                    <span style="color: #009199">{{scope.row.username}}</span>
                                </el-form-item>
                                <el-form-item >
                                     <span slot="label">
                                         <i class="el-icon-user-solid"></i>
                                         昵称
                                    </span>
                                    <span style="color: #009199">{{scope.row.nickname}}</span>
                                </el-form-item>
                                <el-form-item >
                                     <span slot="label">
                                         <i class="el-icon-position"></i>
                                         所在位置
                                    </span>
                                   <span>
                                        经度: <span style="color: #005ba1">{{scope.row.lng}}</span>,
                                        纬度: <span style="color: #00a199">{{scope.row.lat}}</span>
                                   </span>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户名" prop="username" sortable align="center"></el-table-column>
                    <el-table-column prop="nickname" label="昵称" align="center"></el-table-column>
                    <el-table-column prop="perm" label="所属权限" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.perm == 'admin'" style="color: #FF9900">管理员</span>
                            <span v-else style="color: #8F2139">用户</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="账号情况" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.status == 1" style="color: #8F2139">禁用</span>
                            <span v-else style="color: #005ba1" >在用</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200px"  fixed="right">
                        <template slot-scope="scope">
                            <el-button icon="el-icon-edit" type="text" @click="EditUserInfo(scope.row.username,scope.row.nickname)"  style="color: #0a3d62">修改</el-button>
                            <el-button icon="el-icon-circle-close" v-if="scope.row.status == 0" type="text" @click="banUser(scope.row.username)" style="color: #ff7700; padding-left: 4px">禁用</el-button>
                            <el-button icon="el-icon-refresh-left" v-else type="text" @click="unbanUser(scope.row.username)" style="color: #a88d04; padding-left: 4px">解禁</el-button>
                            <el-button icon="el-icon-delete"  type="text" @click="removeUser(scope.row.username)" style="color: red; padding-left: 4px">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-scrollbar>
            <!--      分页区域-->
            <div class="fenye">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pagenum"
                        :page-size="queryInfo.pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>
            <div style="height: 20vh"></div>
        </el-card>

        <el-dialog
                title="摩尔改名区"
                :visible.sync="toEdit"
                width="47.9%" @close="EditDialogClosed">
            <!--      内容主体区域-->
            <el-form :model="userForm" :rules="rules" ref="userFormRef"  status-icon label-width="100px">
                <el-form-item label="新昵称: " required prop="nickname">
                    <el-input v-model="userForm.nickname" placeholder="请输入想修改的昵称"></el-input>
                </el-form-item>
            </el-form>
            <!--      底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-row>
                    <el-col :span="4" :offset="5">
                        <el-button type="danger" @click="EditName()">保 存</el-button>
                    </el-col>
                    <el-col :span="4" :offset="5">
                        <el-button type="danger" plain class="white_btn" style="margin-left: 40px" @click="EditDialogClosed()">重 置</el-button>
                    </el-col>
                </el-row>
            </span>
        </el-dialog>

        <el-dialog
                title="摩尔登记区"
                :visible.sync="toAdd"
                width="47.9%" @close="AddDialogClosed">
            <el-form status-icon ref="registerFormRef" label-width="100px" :rules="rules1" :model="registerForm">
                <el-form-item label="账号名" prop="username">
                    <el-input prefix-icon="el-icon-user" placeholder="账号名" v-model="registerForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input  type="password" autocomplete="false" placeholder="密码" prefix-icon="el-icon-lock" v-model="registerForm.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="pwd">
                    <el-input  type="password" autocomplete="false" placeholder="确认密码" prefix-icon="el-icon-lock" v-model="registerForm.pwd"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input prefix-icon="el-icon-picture-outline-round"  placeholder="昵称" v-model="registerForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="权限" prop="perm">
                    <el-radio v-model="registerForm.perm" label="user" border>普通用户</el-radio>
                    <el-radio v-model="registerForm.perm" label="admin" border>管理员</el-radio>
                </el-form-item>
            </el-form>
            <!--      底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-row>
                    <el-col :span="4" :offset="5">
                    <el-button  type="danger" @click="register">确 定</el-button>
                    </el-col>
                    <el-col :span="4" :offset="5">
                        <el-button type="danger" plain  style="margin-left: 40px" @click="AddDialogClosed()">重 置</el-button>
                    </el-col>
                </el-row>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    var md5 = require('md5')
    export default {
        name: "Manage",
        data(){
            return{
                loading:true,
                total: 0,
                AllUserList:[],
                queryInfo: {
                    // 模糊搜索
                    searchInfo: '',
                    // 当前页数
                    pagenum: 1,
                    pagesize: 5
                },
                registerForm: {
                    username: '',
                    password: '',
                    nickname: '',
                    pwd:'',
                    perm:'user'
                },
                rules1: {
                    username: [
                        {required: true, message: '请输入帐户名', trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        // { pattern: '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$', message: '需同时含有数字和字母，且长度在6-16位之间' }
                    ],
                    pwd: [
                        {required: true, message: '请再次输入密码', trigger: 'blur'},
                        {
                            validator: (rule, value, callback) => {
                                if (value === '') {
                                    callback(new Error('请再次输入密码'))
                                } else if (value !== this.registerForm.password) {
                                    callback(new Error('两次输入密码不一致'))
                                } else {
                                    callback()
                                }
                            },
                            trigger: 'blur'
                        },
                    ],
                    perm: {required: true, message: '请选择权限', trigger: 'blur'},
                },
                selected:'',
                //设置row-key只展示一行
                expands: [],
                getRowKeys(row) {//只展开一行放入当前行id
                    return row.id
                },
                toEdit: false,
                userForm:{
                    nickname:'',
                    username:''
                },
                rules: {
                    nickname: [
                        { required: true, message: '请输入您想要修改的昵称', trigger: 'blur' },
                    ],
                },
                ByRole:'all',
                ByRoleName:'全部',
                RoleList:[
                    {
                        role:'all',
                        name:'全部'
                    },
                    {
                        role:'user',
                        name:'用户'
                    },
                    {
                        role:'admin',
                        name: '管理员'
                    }
                ],
                toAdd : false,
            }
        },
        created() {
            this.getUserList()
        },
        methods:{
            async getUserList(){
                this.loading =true
                const { data: res } = await this.$http.get('/user/listBy/'+ this.ByRole)
                console.log(res.data)
                if (res.code !== 200) {
                    this.loading = false
                    return this.WarningMsg(res.msg)
                }
                this.AllUserList = res.data
                this.total = this.AllUserList.length
                this.loading = false
            },
            // 监听 pagesize 改变的事件
            handleSizeChange (newSize) {
                this.queryInfo.pagesize = newSize
                this.getUserList()
            },
            // 监听页码值改变的事件
            handleCurrentChange (newPage) {
                // console.log(newPage)
                this.queryInfo.pagenum = newPage
                this.getUserList()
            },
            // 选中该行
            handleSelectionChange(val) {
                this.selected = val;
                // console.log(val)
            },
            EditDialogClosed () {
                this.$refs.userFormRef.resetFields()
            },
            AddDialogClosed(){
              this.$refs.registerFormRef.resetFields()
            },
            EditUserInfo(username,nickname){
                console.log(username)
                this.userForm.username = username
                this.userForm.nickname = nickname
                this.toEdit = true
            },
            async removeUser (username) {
                const confirmResult = await this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(err => err)
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除')
                }
                // console.log('确认删除')
                const { data: res } = await this.$http.delete('/user/fulldelete/'+username)
                if (res.code !== 200) {
                   return this.WarningMsg(res.msg)
                }
                this.$message.success('删除成功!')
                this.getUserList()
            },
            async banUser (username) {
                const confirmResult = await this.$confirm('此操作将禁用该账号, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(err => err)
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消禁用')
                }
                // console.log('确认删除')
                const { data: res } = await this.$http.get('/user/lock/'+username)
                if (res.code !== 200) {
                    return this.WarningMsg(res.msg)
                }
                this.$message.success('禁用成功!')
                this.getUserList()
            },
            async unbanUser (username) {
                const confirmResult = await this.$confirm('此操作将解除禁用该账号, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(err => err)
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消解除禁用')
                }
                // console.log('确认删除')
                const { data: res } = await this.$http.get('/user/unlock/'+username)
                if (res.code !== 200) {
                    return this.WarningMsg(res.msg)
                }
                this.$message.success('解禁成功!')
                this.getUserList()
            },
            async EditName (){
                const { data: res } = await this.$http.post('/user/update/', this.userForm)
                if (res.code !== 200) {
                    return this.WarningMsg(res.msg)
                }
                this.$message.success('修改成功!')
                this.toEdit = false
                this.getUserList()
            },
            // 导出excel
            async handleExport() {
                const confirmResult = await this.$confirm('该操作将导出当前所有人员列表数据，是否继续？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (confirmResult !== 'confirm') {
                    this.WarningMsg('已取消导出')
                }
                this.queryInfo.pagesize = 5000
                var fix = document.querySelector('.el-table__fixed-right');//删除fixed的dom节点
                // console.log(fix)
                let wb;
                this.$nextTick(() => {
                    if (fix) {
                        wb = XLSX.utils.table_to_book(document.querySelector('#exportExcel').removeChild(fix));
                        document.querySelector('#exportExcel').appendChild(fix);//恢复删除fixed的dom节点
                    } else {
                        wb = XLSX.utils.table_to_book(document.querySelector('#exportExcel'));
                    }
                    let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
                    try {
                        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), "摩尔列表.xlsx")
                    } catch (e) {
                        if (typeof console !== 'undefined') console.log(e, wbout)
                    }
                    this.queryInfo.pagesize = 5
                    return wbout;
                })
            },

            // 展开事件----动态获取内嵌表数据
            expandChange(row, expandedRows) {
                var that = this
                if (expandedRows.length) {
                    that.expands = []
                    if (row) {
                        console.log(row)
                        that.expands.push(row.id)
                    }
                }
            },

            selectRole(item){
                this.ByRoleName = item.name
                this.ByRole = item.role
                this.getUserList()
            },
            async register(){
                console.log(this.registerForm)
                if (this.registerForm.password && this.registerForm.username && this.registerForm.nickname){
                    if(this.registerForm.password === this.registerForm.pwd) {
                        var pass = this.registerForm.password
                        this.registerForm.password = md5(pass)
                        this.registerForm.pwd = md5(pass)
                        // console.log(this.registerForm)
                        const { data: res } = await this.$http.post('/user/register',this.registerForm)
                        console.log(res)
                        if (res.code !== 200){
                            return this.$message.error(res.msg)
                        }
                        this.$message.success('登记成功！')
                        this.toAdd = false
                    }
                    else{
                        this.$message.error('请再次确认密码,两次输入不一致')
                    }
                }
                else{
                    this.$message.error('注册信息填写不完整！')
                }
            },
            WarningMsg(msg) {
                const h = this.$createElement;
                this.$notify.warning({
                    title: '提示',
                    message: h('p', {style: 'color: teal'}, msg),
                    offset: 100,
                    duration: 3000
                });
            },
        },
        computed:{
            pagetestlist: function () {
                var search = this.queryInfo.searchInfo
                if (search) {
                    return this.AllUserList.filter(function (data) {
                        return Object.keys(data).some(function (key) {
                            return String(data[key]).toLowerCase().indexOf(search) > -1
                        })
                    })
                }
                return this.AllUserList.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
            }
        }
    }
</script>

<style scoped>
    .fenye{
        float: right;
        margin-top: 30px;
        margin-right: 30px;
    }
    .addcount{
        background: #0a3d62;
        color: white;
        letter-spacing: 1px;
    }
    .addcount:hover, .addcount:active, .addcount:focus{
        background: #005ba1;
        color: ghostwhite;
        letter-spacing: 1px;
    }
    .icon_add{
        width: 10px;
        height: 10px;
        padding-right: 1px;
        vertical-align:middle;
    }
    .sel_btn{
        background: #0a3d62;
        color: white;
    }
    .sel_btn:hover, .sel_btn:active, .sel_btn:focus{
        background: #005ba1;
        color: ghostwhite;
    }
    .el-dropdown-menu__item:not(.is-disabled):hover{
        background-color: #d9e0ef !important;
        color: #0a3d62 !important;
    }
</style>
